//设置
//  SettingController.m
//  BigToBig
//
//  Created by guochuangkeshi on 16/4/26.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "SettingController.h"
#import "ChangeViewController.h"
#import "AboutViewController.h"
#import "HomeViewController.h"
@interface SettingController ()

@property (nonatomic , strong)NSArray *titleArr;
@property (nonatomic ,weak)UILabel *huancunLb;
@end

@implementation SettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLab.text = @"设置";
    titleLab.textColor = [UIColor whiteColor];
    [self setBackBar];
    titleLab.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLab;
    self.navigationController.navigationBar.barTintColor = COLOR_RGBA(77, 155, 255, 1);

    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.rowHeight = 60;
    
    
    
//    [self jisuanCatch];
    
    
}

-(NSArray *)titleArr{
    
    if (_titleArr==nil) {
        _titleArr=@[@"修改密码",@"清理缓存",@"关于大秀创投"];
    }
    return _titleArr;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden=NO;
}

- (void)setBackBar{
    
    BackButton *backBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    [backBtn addTarget:self action:@selector(backController:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
}

- (void)backController:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

#pragma mark 指定有多少个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

#pragma mark 指定每个分区中有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==0) {
        return 3;
    }else{
        return 1;
    }

}

#pragma mark 绘制cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID =@"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    if (indexPath.section==0) {
        
        cell.textLabel.text = self.titleArr[indexPath.row];
        
        if (indexPath.row == 1) {
            
             UILabel *huancunLb = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth - 85, 5, 100, cell.contentView.bounds.size.height)];
            huancunLb.textColor = [UIColor blackColor];
            self.huancunLb = huancunLb;
           NSString *cacheSize = [self cacheSize];
            huancunLb.text = cacheSize;
            [cell.contentView addSubview:huancunLb];
            cell.accessoryType = UITableViewCellAccessoryNone;
            
        }
    }else{
        cell.textLabel.text= @"退出";
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}
#pragma mark 分区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .1;
}

#pragma mark tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==0 && indexPath.section==0) {
        ChangeViewController *changeVc=[[ChangeViewController alloc]init];
        [self.navigationController pushViewController:changeVc animated:YES];
    }else if (indexPath.row==1){
        [self removeCache];
    }else if (indexPath.row==2){
        AboutViewController *aboutVc=[[AboutViewController alloc]init];
        [self.navigationController pushViewController:aboutVc animated:YES];
    }else{
        
        NSUserDefaults* isLogin = [NSUserDefaults standardUserDefaults];
        [isLogin setBool:NO forKey:@"isOn"];
        [isLogin synchronize];
        
        
//        NSUserDefaults* name = [NSUserDefaults standardUserDefaults];
//        [name setObject:nil forKey:@"name"];
//        [name synchronize];
        
//        NSUserDefaults* inputSecreate = [NSUserDefaults standardUserDefaults];
//        [inputSecreate setObject:nil forKey:@"Secreate"];
//        [inputSecreate synchronize];
        
        //退出登录时移除用户id因为用户id是唯一的如果不移除的话再根据id为key取值的地方将取的是同一个id
        
//        NSUserDefaults* userID = [NSUserDefaults standardUserDefaults];
//        [userID setObject:nil forKey:@"userID"];
//        [userID synchronize];
        
//        NSUserDefaults* sdkLoginName = [NSUserDefaults standardUserDefaults];
//        [sdkLoginName setObject:nil forKey:@"loginName"];
//        [sdkLoginName synchronize];

        [UIView animateWithDuration:1.0 animations:^{
            
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = @"正在退出...";
            HUD.mode = MBProgressHUDModeIndeterminate;
            [HUD hide:YES afterDelay:1.0];
            
        } completion:^(BOOL finished) {
            
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[HomeViewController new]];
            
            KeyWindow.rootViewController = nav;
            
        }];

    }
}

-(void)removeCache
{
    //===============清除缓存==============
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *p in files)
    {
        NSError *error;
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
    HUD.labelText = @"正在清理";
    HUD.mode = MBProgressHUDModeIndeterminate;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        HUD.labelText = @"清理完成";
        HUD.mode =MBProgressHUDModeText;
        [HUD hide:YES afterDelay:.5];
        self.huancunLb.text = @"0.00Kb";
    });
    
}
//- (void)jisuanCatch{
//
//    NSString * path = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/ImageCaches"];
//    NSDictionary * dict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
//    NSLog(@"%@",[dict objectForKey:NSFileSize]);
//}

#pragma mark 计算缓存大小
- (NSString *)cacheSize{
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    long long sumSize = 0;
    
    for (NSString *p in files)
    {
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        
        if([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil]fileSize];
            
            sumSize +=fileSize;
        }
    }
    
    float total = sumSize/1000;
    
    NSString *cacheSize = [NSString stringWithFormat:@"%.2fKb",total];
    
    return cacheSize;
    
}
@end
